import requests
import json

url = "https://api-s1.aiearth.dev/v1/chat/completions"
api_key = "sk-k1pYffA3tew730yv3ZIBTIm4wOzWYWytW8TYOgyMTWSwoe4Y"  # 替换成你的有效API Key

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
    "Accept": "text/event-stream",  # 关键：声明接受事件流
    "Cache-Control": "no-cache"
}

payload = {
    "max_tokens": 1024,
    "model": "qwen-max-latest",
    "temperature": 0.5,
    "top_p": 1,
    "presence_penalty": 0,
    "frequency_penalty": 0,
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "你好"
        }
    ],
    "stream": True  # 启用流式响应
}

# 发送请求并处理流式响应
response = requests.post(
    url,
    headers=headers,
    json=payload,
    stream=True  # 关键：保持连接开放
)

full_response = ""
for line in response.iter_lines():
    if line:
        decoded_line = line.decode('utf-8')
        if decoded_line.startswith('data:'):
            data_str = decoded_line.replace('data: ', '', 1).strip()
            if data_str == '[DONE]':
                print("\n[Stream completed]")
                break
            
            try:
                data = json.loads(data_str)
                if 'choices' in data:
                    content = data['choices'][0]['delta'].get('content', '')
                    print(content, end='', flush=True)  # 实时打印
                    full_response += content
            except json.JSONDecodeError:
                pass

print("\nFull response:", full_response)